package edu.hawaii.its381b.server;

import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import edu.hawaii.its381b.client.GreetingService;
import edu.hawaii.its381b.shared.FieldVerifier;
import edu.hawaii.its381b.shared.Score;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

/**
 * The server side implementation of the RPC service.
 */
@SuppressWarnings("serial")
public class GreetingServiceImpl extends RemoteServiceServlet implements
		GreetingService {
	
	public String putScore(Score s) throws IllegalArgumentException {

		// Persist the player object
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			// create or modify entities via the pm
			pm.makePersistent(s);
		} finally {
			pm.close();
		} 
		return getScoreboard();
	}
	
	@SuppressWarnings("unchecked") // at your own risk
	public String getScoreboard() throws IllegalArgumentException {

		StringBuffer buffer = new StringBuffer();
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query query = pm.newQuery(Score.class);
		query.setOrdering("score desc");
		query.setRange(0L, 10L);

		int i = 0;
		try {
			List<Score> results = (List<Score>)query.execute();	
			buffer.append("<table class='scores'>");
			buffer.append("<tr><th>Rank</th><th>Name</th><th>Score</th></tr>");
			if(!results.isEmpty()) {
				for(Score s : results) {
					buffer.append("<tr><td>" + (++i) + "</td><td>" + s.getName() + "</td><td>" + s.getScore() + "</td></tr>");
				}
			}
			buffer.append("</table>");
		} finally {
			query.closeAll();
		}
		return buffer.toString();
	}
	
	@SuppressWarnings("unchecked") // at your own risk
	public String getTopScore() throws IllegalArgumentException {

		StringBuffer buffer = new StringBuffer();
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query query = pm.newQuery(Score.class);
		query.setOrdering("score desc");
		query.setRange(0L, 1L);

		try {
			List<Score> results = (List<Score>)query.execute();	
			if(results.isEmpty()) {
				buffer.append("0");
			} else {
				buffer.append(results.get(0).getScore());
			}
		} finally {
			query.closeAll();
		}
		return buffer.toString();
	}

	/**
	 * Escape an html string. Escaping data received from the client helps to
	 * prevent cross-site script vulnerabilities.
	 * 
	 * @param html the html string to escape
	 * @return the escaped string
	 */
	private String escapeHtml(String html) {
		if (html == null) {
			return null;
		}
		return html.replaceAll("&", "&amp;").replaceAll("<", "&lt;")
				.replaceAll(">", "&gt;");
	}
}
